package com.itheima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.search.mapper.ApUserSearchMapper;
import com.itheima.search.pojo.ApUserSearch;
import com.itheima.search.service.ApUserSearchService;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @description <p>APP用户搜索信息 业务实现</p>
 *
 * @version 1.0
 * @package com.itheima.search.service.impl
 */
@Service
public class ApUserSearchServiceImpl extends ServiceImpl<ApUserSearchMapper, ApUserSearch> implements ApUserSearchService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 保存用户的搜索记录
     *
     * @param searchWords
     */
    @Override
    //异步，指定线程池名称
    @Async("searchWordThreadPool")
    public void saveSearchWords(Long loginUserId, String searchWords) {
        /*try {
            System.err.println("我要睡10秒。。。。");
            Thread.sleep(10000);
            System.err.println("我10秒后。。。。");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        //1. 定义 key
        String key = "USER_SEARCH_" + loginUserId;
        //2. 查询key的值
        String redisJson = stringRedisTemplate.opsForValue().get(key);
        //3. 有值
        List<String> list = new ArrayList<>();
        if(!StringUtils.isEmpty(redisJson)) {
            //3.1 转成java中的list
            list = JSON.parseArray(redisJson, String.class);
        }
        //4. 没值
        //4.1 构建list,添加关键词
        add2List(list, searchWords);
        //5. 转成json字符串，
        redisJson = JSON.toJSONString(list);
        //存入redis，存活时长为30天
        stringRedisTemplate.opsForValue().set(key, redisJson, 30, TimeUnit.DAYS);
    }

    private void add2List(List<String> list, String s) {
        // 判断集合中是否包含值
        int index = list.indexOf(s);
        if(index==0){
            return;
        }else if (index > 0){
            // 存在
            list.remove(index);
        }
        int size = list.size();
        if(size == 10){
            list.remove(size-1);
        }

        list.add(0,s);
    }
}
